import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '@/layout/MainLayout.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: MainLayout,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          component: () => import('@/views/dashboard/index.vue')
        },
        {
          path: 'user',
          children: [
            {
              path: 'list',
              component: () => import('@/views/user/UserList.vue')
            }
          ]
        },
        {
          path: 'course',
          children: [
            {
              path: 'list',
              component: () => import('@/views/course/CourseList.vue')
            },
            {
              path: 'detail/:id',
              component: () => import('@/views/course/CourseDetail.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router 